package com.yoyo.ad.presenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import com.yoyo.ad.bean.AdConfig;
import com.yoyo.ad.bean.JsonStringBean;
import com.yoyo.ad.bean.YoYoAdBean;
import com.yoyo.ad.confusion.AdLocalSourceRecord;
import com.yoyo.ad.main.IAdIpCount;
import com.yoyo.ad.main.IUpdateView;
import com.yoyo.ad.api.ApiManage;
import com.yoyo.ad.api.IAdApi;
import com.yoyo.ad.contract.AdContract;
import com.yoyo.ad.utils.Aes;
import com.yoyo.ad.utils.BasePresenter;
import com.yoyo.ad.utils.GreenDaoManager;
import com.yoyo.ad.utils.SystemUtil;
import com.google.gson.Gson;
import com.yoyo.ad.yoyo.IYoyoAdListener;

import org.json.JSONObject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static com.yoyo.ad.api.YoYoConfig.MEDIA_ID;


@SuppressLint("CheckResult")
public class AdPresenter extends BasePresenter<AdContract.View> implements AdContract.Presenter {

    private final String NET_ERROR = "网络繁忙";

    public AdPresenter(Context context, AdContract.View view) {
        super(context, view);
    }

    @Override
    public void qryAdConfigList() {
        if (AdLocalSourceRecord.isAdConfigTime(mContext)) {
            getAdConfigOffline();
        } else {
            getAdConfigOnline();
        }
    }

    @Override
    public void qryCIpShowCount(final String position, final IAdIpCount iAdIpCount) {
        StringBuilder builder = new StringBuilder();
        builder.append("mediaId=").append(MEDIA_ID).append("&adIdStr=").append(position);
        Log.i("openPushAuthority==", builder.toString());
        String key = Aes.encode(builder.toString(), Aes.keyBytes);
        ApiManage.getInstance().getApi(IAdApi.class)
                .qryCIpShowCount(key)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<JsonStringBean>() {
                    @Override
                    public void accept(JsonStringBean responseBody) throws Exception {
                        if (responseBody.getResp_status().equals("1000")) {
                            iAdIpCount.adIpCounts(position.split(","), new JSONObject(new Gson().toJson(responseBody.getResp_data())));
                        } else {
                            mView.onAdFail(responseBody.getResp_info());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        mView.onAdFail(NET_ERROR);
                    }
                });
    }

    @Override
    public void addCIpShowCount(long adId) {
        StringBuilder builder = new StringBuilder();
        builder.append("mediaId=").append(MEDIA_ID).append("&adId=").append(adId);
        Log.i("openPushAuthority==", builder.toString());
        String key = Aes.encode(builder.toString(), Aes.keyBytes);
        ApiManage.getInstance().getApi(IAdApi.class)
                .addCIpShowCount(key)
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<JsonStringBean>() {
                    @Override
                    public void accept(JsonStringBean jsonStringBean) {

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {

                    }
                });
    }

    @Override
    public void addBounded(boolean isIntercept, String boundedTime, String adPositionBoundedJson, String adBoundedJson, final IUpdateView iUpdateView) {
        if (isIntercept)
            if (!AdLocalSourceRecord.canUpload(mContext)) {
                //受限上报限制
                return;
            }
//            Log.e("ad_intercept_report",adPositionBoundedJson+"____"+adBoundedJson);
        StringBuilder builder = new StringBuilder();
        builder.append("mediaId=").append(MEDIA_ID)
                .append("&imei=").append(SystemUtil.getIMEI(mContext))
                .append("&boundedTime=").append(boundedTime)
                .append("&adPositionBoundedJson=").append(adPositionBoundedJson)
                .append("&adBoundedJson=").append(adBoundedJson);
        Log.i("openPushAuthority==", builder.toString());
        String key = Aes.encode(builder.toString(), Aes.keyBytes);
        ApiManage.getInstance().getApi(IAdApi.class)
                .addBounded(key)
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<JsonStringBean>() {
                    @Override
                    public void accept(JsonStringBean responseBody) {
                        if (responseBody.getResp_status().equals("1000")) {
                            iUpdateView.success();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {

                    }
                });
    }

    @Override
    public void addStatistics(String jsonString, final IUpdateView iUpdateView) {
        StringBuilder builder = new StringBuilder();
        builder.append("imei=").append(SystemUtil.getIMEI(mContext))
                .append("&mediaId=").append(MEDIA_ID)
                .append("&eventBoundedJson=").append(jsonString);
        Log.i("openPushAuthority==", builder.toString());
        String key = Aes.encode(builder.toString(), Aes.keyBytes);
        ApiManage.getInstance().getApi(IAdApi.class)
                .addEventBounded(key)
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<JsonStringBean>() {
                    @Override
                    public void accept(JsonStringBean responseBody) {
                        if (responseBody.getResp_status().equals("1000")) {
                            iUpdateView.success();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                });
    }

    @Override
    public Disposable qryYoyoAdConfig(String positionId, final IYoyoAdListener iYoyoAdListener) {
        StringBuilder builder = new StringBuilder();
        builder.append("positionId=").append(positionId);
        Log.i("openPushAuthority==", builder.toString());
        String key = Aes.encode(builder.toString(), Aes.keyBytes);
        return ApiManage.getInstance().getApi(IAdApi.class)
                .qryYoyoAdConfig(key)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<YoYoAdBean>() {
                    @Override
                    public void accept(YoYoAdBean responseBody) {
                        if (responseBody.getResp_status().equals("1000")) {
                            iYoyoAdListener.success(responseBody);
                        } else {
                            iYoyoAdListener.fail(responseBody.getResp_info());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        iYoyoAdListener.fail(NET_ERROR);
                        throwable.printStackTrace();
                    }
                });
    }

    private void getAdConfigOffline() {
        GreenDaoManager.getInstance().getDaoSession().getAdConfigListBeanDao().rx().count()
                .subscribeOn(rx.schedulers.Schedulers.io())
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long count) {
                        if (count < 1) {
                            AdPresenter.this.getAdConfigOnline();
                        } else {
                            mView.onAdSuccess();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        AdPresenter.this.getAdConfigOnline();
                        mView.onAdFail("");
                    }
                });
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    private void getAdConfigOnline() {
        StringBuilder builder = new StringBuilder();
        builder.append("mediaId=").append(MEDIA_ID)
                .append("&flag=").append(1);
        Log.i("openPushAuthority==", builder.toString());
        String key = Aes.encode(builder.toString(), Aes.keyBytes);
        ApiManage.getInstance().getApi(IAdApi.class)
                .qryAdConfigList(key)
                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<AdConfig>() {
                    @Override
                    public void accept(AdConfig responseBody) {
                        if (responseBody.getResp_status().equals("1000")) {
                            GreenDaoManager.getInstance().getDaoSession().getAdConfigListBeanDao()//.rx()
                                    .insertOrReplaceInTx(responseBody.getResp_data().getAdConfigList());
                            GreenDaoManager.getInstance().getDaoSession().getAdSourceConfigListBeanDao()
                                    .insertOrReplaceInTx(responseBody.getResp_data().getAdSourceConfigList());
                            AdLocalSourceRecord.setAdConfigTime(mContext);
                            AdLocalSourceRecord.setOvertime(mContext, responseBody.getResp_data().getOvertime());
                            AdLocalSourceRecord.setProbability(mContext, responseBody.getResp_data().getProbability());
                            if (mView != null)
                                mView.onAdSuccess();
                        } else {
                            if (mView != null)
                                mView.onAdFail("");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        if (mView != null)
                            mView.onAdFail("");
                    }
                });
    }
}

